// components/x-lyric/x-lyric.js
let lyricHeight = 0
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isLyricShow: {
      type: Boolean,
      value: false
    },
    lyric: String
  },
  observers: {
    lyric(lrc) {
      if (lrc == "无歌词") {
        this.setData({
          lyricLlist: [{
            lrc,
            time: 0
          }],
          nowLyricIndex: -1
        })
      } else {
        this._parseLyric(lrc)
      }
      // console.log(lrc)   
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    lyricLlist: [],
    nowLyricIndex: 0, // 当前歌词选中的索引
    scrollTop: 0, // 歌词滚动
  },
  lifetimes: {
    ready() {
      wx.getSystemInfo({
        success: function(res) {
          // console.log(res)
          lyricHeight = res.screenWidth / 750 * 64
        },
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    update(currentTime) {
      // let _currentTime = currentTime
      // console.log(_currentTime)
      let lyricList = this.data.lyriclist
      // console.log(lyricList)
      if (lyricList.length == 0) {
        return
      }
      if (currentTime > lyricList[lyricList.length - 1].time) {
        if (this.data.nowLyricIndex != -1) {
          this.setData({
            nowLyricIndex: -1,
            scrollTop: lyricList.length * lyricHeight,
          })
        }
      }
      for (let i = 0, len = lyricList.length; i < len; i++) {
        if (currentTime <= lyricList[i].time) {
          // console.log(_currentTime)
          // console.log(currentTime)
          // console.log(lyricList[i].time)
          this.setData({
            nowLyricIndex: i - 1,
            scrollTop: (i - 1) * lyricHeight
          })
          break
        }
      }
    },
    _parseLyric(sLyric) {
      let line = sLyric.split('\n')
      // console.log(line)
      let _lyriclist = []
      line.forEach(elem => {
        let time = elem.match(/\[(\d{2,}):(\d{2,})(?:\.(\d{2,3}))?]/g)
        if (time != null) {
          // console.log(time)
          let lrc = elem.split(time)[1]
          let timeReg = time[0].match(/(\d{2,}):(\d{2,})(?:\.(\d{2,3}))?/)
          // console.log(lrc)
          // console.log(timeReg)
          let time2Seconds = parseInt(timeReg[1]) * 60 + parseInt(timeReg[2]) + parseInt(timeReg[3]) / 1000
          _lyriclist.push({
            lrc,
            time: time2Seconds,
          })
        }
      })
      this.setData({
        lyriclist: _lyriclist
      })
    }
  }
})